#!/bin/bash
# OpenModelica TLM start-up script
# Start with 6 arguments:
# 1 XModelName (XModel directory) 
# 2 start-time 
# 3 end-time 
# 4 max-time-step 
# 5 server-name:port 
# 6 model-file 

# The following lines need to be adjusted for each system!
OpenModelicaPath=$OPENMODELICAHOME
OMC_Cmd="${OpenModelicaPath}/bin/omc"

if [ -z "$OpenModelicaPath" ] ; then
    echo "$0 : No OpenModelicaPath or OPENMODELICAHOME set, give up."
    exit 1
fi


LD_LIBRARY_PATH=${OpenModelicaPath}/lib

TLMCONFIGFILE=tlm.config

if [ ! -f "$1/$6" ] ; then 
    if [ ! -f "$1/$6.mo" ] ; then 
	echo Usage: 
	echo $0 XModelName start-time end-time max-time-step server-name:port model-file 
	echo $6
	pwd
	exit 1
    fi
fi

echo execution directory is $1
cd $1

echo Starting a OpenModelica simulation with input file: $6
echo Make sure that: 
echo time = $2
echo timeEnd = $3
echo MaxTimeStep "<"= $4
echo 

echo Writing caseID $1 and server name $5 to file $TLMCONFIGFILE
echo $1 > $TLMCONFIGFILE 
echo $5 >> $TLMCONFIGFILE
echo $2 >> $TLMCONFIGFILE
echo $3 >> $TLMCONFIGFILE
echo $4 >> $TLMCONFIGFILE

MOSFILE=$1.mos
MODELNAME=`basename $6 .mo` 
INTERVAL_STR="($3-$2)/($4)"
echo INTERVAL_STR=$INTERVAL_STR
INTERVAL_STR="scale=8;${INTERVAL_STR/e/*10^}"
echo INTERVAL_STR=$INTERVAL_STR
INTERVALS=`echo $INTERVAL_STR | bc`
echo INTERVALS=$INTERVALS

echo Writing $MOSFILE
echo // Autogenerated modelica script for TLM cosimulation > $MOSFILE
echo "loadModel(Modelica);" >> $MOSFILE
echo "getErrorString();" >> $MOSFILE
echo "loadFile(\"${OMTLMSimulatorPath}/bin/OpenModelica/OM_TLM.mo\");" >> $MOSFILE
echo "getErrorString();" >> $MOSFILE
echo "loadFile(\"$MODELNAME.mo\");" >> $MOSFILE
echo "getErrorString();" >> $MOSFILE
echo "setLinkerFlags(\"-L/usr/lib64 -lstdc++\");" >> $MOSFILE
echo "simulate($MODELNAME, startTime=$2, stopTime=$3, method=\"dassl\", outputFormat=\"mat\", simflags=\"-noEquidistantTimeGrid -maxStepSize=$4\");" >> $MOSFILE
echo "getErrorString();" >> $MOSFILE

echo Starting OpenModelica
echo $OMC_Cmd $MOSFILE

$OMC_Cmd $1.mos > $1.simlog
